<?php

namespace Iwester\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Iwester\Http\Model\User\User;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Iwester\Http\Requests\ResetPasswordRequest;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/admin';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * 重置密码
     * @param ResetPasswordRequest $request
     * @return array
     */
    public function resetPassword(ResetPasswordRequest $request)
    {
        try {
            \DB::beginTransaction();
            $vercode = $request->get('vercode', '');
            $type = $request->get('type', 'reset');
            $data = $request->get('user', []);
            $checkVercode = $this->checkVercode($request->get('_token', false), $data['email'], $type, $vercode);
            if (!$checkVercode) return ['code' => 201, 'message' => '验证码错误！'];
            $user = User::where('email', $data['email'])->first();
            if (!$user) return ['code'=> 201, 'message'=> '邮箱用户不存在~'];
            $user->password = bcrypt($data['password']);
            $user->save();
            \DB::commit();
            \Auth::attempt(['email' => $data['email'], 'password' => $data['password']]);
            return ['code' => 200, 'message' => '密码重置成功，正在登陆...！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => '保存失败！'];
        }
    }

    /**
     * 验证验证码
     * @param $token
     * @param $email
     * @param $vercode
     * @return bool
     */
    public function checkVercode($token, $email, $type, $vercode){
        return true;
        $key = $email.$token.$type;
        $cacheVercode = \Cache::pull($key);
        if ($vercode == $cacheVercode){
            return true;
        }
        return false;
    }
}
